﻿using System;
using System.Text;
using System.Net;
using System.IO;

namespace Common
{
    public class AjaxNet
    {
        protected CookieContainer _cookies = new CookieContainer();
        private WebResponse _response;
        private Encoding _encoding;
        private HttpWebRequest _request;
        private int _timeout;
        public AjaxNet()
        {
            _encoding = Encoding.Default;
            _timeout = 30000;
        }
        public AjaxNet(Encoding encod)
            : this()
        {
            _encoding = encod;
        }
        public AjaxNet(string encod)
            : this(Encoding.GetEncoding(encod))
        {
        }
        public AjaxNet(Encoding encod, CookieContainer cookies)
            : this(encod)
        {
            _cookies = cookies;
        }
        /// <summary>
        /// GET形式发送数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="referer"></param>
        /// <returns></returns>
        public AjaxNet doGet(string url, string referer)
        {
            try
            {
                GC.Collect();
                _request = (HttpWebRequest)WebRequest.Create(url);
                _request.CookieContainer = this._cookies;
                _request.Timeout = _timeout;
                _request.Method = "get";
                _request.Referer = referer;
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)";
                _rstring = null;
                _response = _request.GetResponse();
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return this;
        }
        /// <summary>
        /// POST形式发送数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="referer"></param>
        /// <returns></returns>
        public AjaxNet doPost(string url, string postData, string referer)
        {
            try
            {
                GC.Collect();
                byte[] bytes = Encoding.UTF8.GetBytes(postData);
                _request = (HttpWebRequest)WebRequest.Create(url);
                _request.Method = "POST";
                _request.Timeout = _timeout;
                _request.ContentType = "application/x-www-form-urlencoded";
                _request.Referer = referer;
                _request.Accept = "application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, */*";
                _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)";
                _request.ContentLength = bytes.Length;
                _request.CookieContainer = this._cookies;
                Stream requestStream = _request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                _rstring = null;
                _response = _request.GetResponse();

            }
            catch (Exception exception)
            {
                throw exception;
            }
            return this;
        }

        public WebResponse Response
        {
            get { return _response; }
        }

        public Stream ResponseStream
        {
            get
            {
                if (_response != null)
                    return _response.GetResponseStream();
                else
                    return null;
            }
        }
        string _rstring = null;
        public String ResponseString
        {
            get
            {
                if (_rstring == null)
                {
                    try
                    {
                        _rstring = StreamReader.ReadToEnd();
                    }
                    catch
                    {
                        return "";
                    }
                }
                return _rstring;
            }
        }
        public StreamReader StreamReader
        {
            get
            {
                return new StreamReader(ResponseStream, Encoding);
            }
        }
        public StringReader StringReader
        {
            get
            {
                return new StringReader(ResponseString);
            }
        }
        public Encoding Encoding
        {
            get
            {
                return _encoding;
            }
            set
            {
                _encoding = value;
            }
        }
        public CookieContainer Cookies
        {
            get
            {
                return _cookies;
            }
            set
            {
                _cookies = value;
            }
        }
        public void SetCookies(string cookieHeader, string domain)
        {
            string[] temp = cookieHeader.Split(';');
            for (int i = 0; i < temp.Length; i++)
            {
                string[] cookieNameValue = temp[i].Split('=');
                Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                ck.Domain = domain;//必须写对
                try
                {
                    Cookies.Add(ck);
                }
                catch { }
            }
        }
        public int TimeOut
        {
            get { return _timeout; }
            set { _timeout = value; }
        }
        public void Abort()
        {
            if (_request != null)
                _request.Abort();
        }
    }
}
